﻿// Copyright (c) Meta Platforms, Inc. and affiliates. 

using TMPro;
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Text))]
/// <summary>
/// Add this class to a gameObject with a Text component and it'll feed it the number of FPS in real time.
/// </summary>
public class FPSCounter : MonoBehaviour
{
    /// <summary>
    /// The frequency at which the FPS counter should update (in seconds)
    /// </summary>
    public float UpdateInterval = 0.3f;

    private float framesAccumulated = 0f;
    private float framesDrawnInTheInterval = 0f;
    private float timeLeft;
    private Text text;
    private int currentFPS;

    /// <summary>
    /// On Start(), we get the Text component and initialize our counter
    /// </summary>
    void Start()
    {
        text = GetComponent<Text>();
        if (text == null)
        {
            Debug.LogWarning("FPSCounter requires a GUIText component.");
            return;
        }
        text.text = "";
        timeLeft = UpdateInterval;
    }

    /// <summary>
    /// On Update, we increment our various counters, and if we've reached our UpdateInterval, we update our FPS counter
    /// with the number of frames displayed since the last counter update
    /// </summary>
    void Update()
    {
        framesDrawnInTheInterval++;
        framesAccumulated += Time.timeScale / Time.deltaTime;
        timeLeft -= Time.deltaTime;

        if (timeLeft <= 0.0)
        {
            currentFPS = (int)Mathf.Clamp(framesAccumulated / framesDrawnInTheInterval, 0, 300);
            text.text = currentFPS.ToString();
            framesDrawnInTheInterval = 0;
            framesAccumulated = 0f;
            timeLeft = UpdateInterval;
        }
    }
}
